﻿using CefSharp.WinForms;
using Com.Geek.Beetle.Config;
using Com.Geek.Beetle.Trasport;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using Com.Geek.Beetle.Protocol;

namespace Com.GeekPlusBeetle
{
    public partial class BeetleMain : Form
    {
        private int _height;     //屏幕高
        private int _width;      //屏幕宽
        private ChromiumWebBrowser _chromeWebBrowser;        //浏览器内核
        private SeedingWall _seedingWall = new SeedingWall();    //播种墙
        /// <summary>
        /// 描述：
        ///     dwFlags Long，下表中标志之一或它们的组合   
        ///     dx，dy Long，根据MOUSEEVENTF_ABSOLUTE标志，指定x，y方向的绝对位置或相对位置      
        ///     cButtons Long，没有使用  
        ///     dwExtraInfo Long，没有使用
        /// </summary>
        /// <param name="dwFlags"></param>
        /// <param name="dx"></param>
        /// <param name="dy"></param>
        /// <param name="cButtons"></param>
        /// <param name="dwExtraInfo"></param>
        /// <returns></returns>
        [System.Runtime.InteropServices.DllImport("user32.dll")]
        private static extern int mouse_event(int dwFlags, int dx, int dy, int cButtons, int dwExtraInfo);
        public class DwFlags
        {
            public static int MOUSEEVENTF_MOVE = 0x0001;// 移动鼠标
            public static int MOUSEEVENTF_LEFTDOWN = 0x0002; //模拟鼠标左键按下
            public static int MOUSEEVENTF_LEFTUP = 0x0004; //模拟鼠标左键抬起
            public static int MOUSEEVENTF_RIGHTDOWN = 0x0008; //模拟鼠标右键按下
            public static int MOUSEEVENTF_RIGHTUP = 0x0010; //模拟鼠标右键抬起
            public static int MOUSEEVENTF_MIDDLEDOWN = 0x0020; //模拟鼠标中键按下
            public static int MOUSEEVENTF_MIDDLEUP = 0x0040; //模拟鼠标中键抬起
            public static int MOUSEEVENTF_ABSOLUTE = 0x8000; //标示是否采用绝对坐标
        }

        public BeetleMain()
        {
            //解决跨线程访问异常
            Control.CheckForIllegalCrossThreadCalls = false;
            InitializeComponent();

            CefSharp.Cef.Initialize();
            _chromeWebBrowser = new ChromiumWebBrowser("http://192.168.1.9/static/html/station/main.html");
            _chromeWebBrowser.Dock = DockStyle.Fill;
            _chromeWebBrowser.RegisterJsObject("Beetle", this);
            this.Controls.Add(_chromeWebBrowser);

            this.KeyPreview = true;      //设置触发窗体控件事件时先经过主窗体

            //设置窗体位置
            this.StartPosition = FormStartPosition.Manual;
            this.Location = new Point(0, 0);

            //获取屏幕宽和高
            this._height = SystemInformation.WorkingArea.Height;
            this._width = SystemInformation.WorkingArea.Width;
            this.Width = _width; this.Height = _height;     //窗体最大尺寸
            this.WindowState = FormWindowState.Maximized;

            //注册回调函数
            this._seedingWall.callBack += new ButtonPressedCallBack(this.ButtonPressed);
        }

        private void BeetleMain_Load(object sender, EventArgs e)
        {
            Point point = this._chromeWebBrowser.PointToScreen(this._chromeWebBrowser.Location);
            //this._seedingWall.TurnOnLight("1A", LightStatus.GREEN_FLASH);
            //Thread.Sleep(100);
            //this._seedingWall.TurnOnLight("2A", LightStatus.READ_FLASH);
        }

        /// <summary>
        /// 模拟鼠标点击
        /// </summary>
        /// <param name="x"></param>
        /// <param name="y"></param>
        public void SimulateMouseClick(int x, int y)
        {
            mouse_event(DwFlags.MOUSEEVENTF_LEFTDOWN | DwFlags.MOUSEEVENTF_LEFTUP, x, y, 0, 0);
        }

        private void button1_Click(object sender, EventArgs e)
        {
            this._seedingWall.TurnOnLight(textBox1.Text, LightStatus.GREEN_FLASH);
        }

        private void button2_Click(object sender, EventArgs e)
        {
            this._seedingWall.Initialize();
        }
    }
    /**********************************************************
    *描述：    
        模拟播种墙
    ***********************************************************/
    public delegate void ButtonPressedCallBack(String buttonID);
    public class SeedingWall
    {
        /// <summary>
        /// 通知客户端的委托
        /// </summary>
        public event ButtonPressedCallBack callBack;
        private Dictionary<String, SeedingWallCell> _cellDict = new Dictionary<string, SeedingWallCell>();
        private SerialTrasport _serialTrasport = new SerialTrasport();

        public Dictionary<String, SeedingWallCell> CellDict
        {
            get { return this._cellDict; }
            set { this._cellDict = value; }
        }
        /// <summary>
        /// 构造函数，初始化播种墙
        /// 
        /// </summary>
        public SeedingWall()
        {
            Char column = '1';
            Char row = 'A';
            int maxColumn = 3, maxRow = 3;
            SeedingWallCell seedingWallCell = null;
            for (int i = 0; i < maxColumn; i++)
            {
                for (int j = 0; j < maxRow; j++)
                {
                    String uniqueID = ((Char)(column + i)) + "" + ((Char)(row + j));
                    seedingWallCell = new SeedingWallCell(uniqueID);
                    seedingWallCell.CellLamp.LampStatus = LightStatus.OFF;
                    _cellDict.Add(uniqueID, seedingWallCell);
                }
            }
            this._serialTrasport.ButtonPressedEvent += new ButtonPressedHandler(this.GetPressedButtonIDHandler);
            //初始换com口
            this._serialTrasport.InitializeComPort(CustomConfig.GetComPortName());
            //初始化灯
            this._serialTrasport.Initialize();
        }

        public void GetPressedButtonIDHandler(String id)
        {
            String rightID = ReverseString(id);
            //再次回调
            callBack(rightID);
        }

        public bool TurnOffLight(String LightID)
        {
            LightID id = GetLightRightID(LightID);
            MessageModel message = new MessageModel(id, LightStatus.OFF);
            return this._serialTrasport.SendData(message);
        }
        public bool TurnOnLight(String lightsID, LightStatus status)
        {
            LightID id = GetLightRightID(lightsID);
            MessageModel message = new MessageModel(id, status);
            return this._serialTrasport.SendData(message);
        }
        private LightID GetLightRightID(String lightID)
        {
            switch (ReverseString(lightID))
            {
                case "A1":
                    return LightID.A1;
                case "A2":
                    return LightID.A2;
                case "A3":
                    return LightID.A3;
                case "B1":
                    return LightID.B1;
                case "B2":
                    return LightID.B2;
                case "B3":
                    return LightID.B3;
                case "C1":
                    return LightID.C1;
                case "C2":
                    return LightID.C2;
                case "C3":
                    return LightID.C3;
                default:
                    return LightID.NULL;
            }
        }

        /// <summary>
        /// 描述：
        ///     获取播种墙
        /// </summary>
        /// <returns></returns>
        public String GetSeedingWall()
        {
            String cellsID = "";
            foreach (var cell in this._cellDict)
            {
                cellsID += cell.Key + ",";
            }
            return cellsID.Substring(0, cellsID.LastIndexOf(","));
        }

        /// <summary>
        /// 描述：
        ///     获取播种墙灯的状态
        /// </summary>
        /// <returns></returns>
        public String GetLampsStaus()
        {
            String status = "";
            foreach (var cell in this._cellDict)
            {
                status += ((short)(cell.Value.CellLamp.LampStatus)) + ",";
            }
            return status.Substring(0, status.LastIndexOf(","));
        }

        /// <summary>
        /// 初始化播种墙
        /// </summary>
        public void Initialize()
        {
            this._serialTrasport.Initialize();
        }
        public String ReverseString(String str)
        {
            char[] chars = str.ToCharArray();
            Array.Reverse(chars);
            return new String(chars);
        }


        /**********************************************************
        *描述：    
            播种墙单元格
        ***********************************************************/
        public class SeedingWallCell
        {
            public JobButton CellButton { get; }        //按钮
            public CargoBox CellCargoBox { get; }       //物料箱
            public Lamp CellLamp { get; }       //灯

            public String CellID { get; set; }       //单元格ID

            public SeedingWallCell(String cellID)
            {
                this.CellID = cellID;
                this.CellButton = new JobButton();
                this.CellCargoBox = new CargoBox();
                this.CellLamp = new Lamp(cellID);
            }

            /**********************************************************
            *描述：    
                播种墙按钮
            ***********************************************************/
            public class JobButton
            {

            }
            /**********************************************************
            *描述：    
                播种墙箱子
            ***********************************************************/
            public class CargoBox
            {

            }
            /**********************************************************
            *描述：    
                灯
            ***********************************************************/
            public class Lamp
            {

                public String ID { get; set; }       //灯标识

                public LightStatus LampStatus { get; set; }
                /// <summary>
                /// 描述：
                ///     设置灯的id
                /// </summary>
                /// <param name="id"></param>
                public Lamp(String id)
                {
                    this.ID = id;
                }

            }
        }

    }
}
